package org.osflash.signals;

import flash.display.Sprite;
import flash.events.Event;
import flash.system.System;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.utils.GetTimer;

@:meta(SWF(width=800,height=600,frameRate=64,backgroundColor=0x333333))
class DispatchPerformance extends Sprite {

	var FPS : Int;
	var N : Int;
	var NUM_LISTENERS : Int;
	var NUM_ITERATIONS : Int;
	var MAX_SCORE : Int;
	var _out0 : TextField;
	var _out1 : TextField;
	var _t0 : Int;
	var _s : ISignal;
	var _d : Int;
	var _f : Int;
	var _min : Int;
	var _max : Int;
	public function new() {
		FPS = 64;
		N = 4;
		NUM_LISTENERS = 1 << (N - 1);
		NUM_ITERATIONS = 80000 / N;
		MAX_SCORE = NUM_LISTENERS * NUM_ITERATIONS * FPS;
		stage.frameRate = FPS;
		_out0 = new TextField();
		_out0.defaultTextFormat = new TextFormat("arial", 24, 0xff00ff);
		_out0.autoSize = TextFieldAutoSize.LEFT;
		_out0.x = 0x20;
		_out0.y = 0x20;
		_out1 = new TextField();
		_out1.defaultTextFormat = new TextFormat("arial", 24, 0xff00ff);
		_out1.autoSize = TextFieldAutoSize.LEFT;
		_out1.x = 0x200;
		_out1.y = 0x20;
		_s = new Signal();
		var i : Int = 0;
		while(i < NUM_LISTENERS) {
			_s.add(function() : Void {
				_d++;
			}
);
			++i;
		}
		addChild(_out0);
		addChild(_out1);
		addEventListener(Event.ENTER_FRAME, onEnterFrame);
	}

	function onEnterFrame(event : Event) : Void {
		var t1 : Int = getTimer();
		if((t1 - _t0) >= 1000)  {
			_out0.text = _d + "/" + MAX_SCORE + " = " + Math.round(_d / MAX_SCORE * 100.0) + "%
" + _f + "fps
" + (System.totalMemory >> 20) + "mb
" + _min + "ms
" + _max + "ms";
			_d = 0;
			_f = 0;
			_t0 = t1;
		}
		_f++;
		var n : Int = NUM_ITERATIONS + 1;
		var m0 : Int = getTimer();
		while(--n != 0)_s.dispatch();
		var dt : Int = (getTimer() - m0);
		if(dt < _min) _min = dt;
		if(dt > _max) _max = dt;
		_out1.text = dt + "ms";
	}

}

